/**
 *
 */
package com.rf.richfitwheel.admin.sys.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.shiro.PasswordExpired;
import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.*;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.MapCaseUtil;
import com.rf.richfitwheel.admin.utils.PasswordHelper;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.session.Session;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hushouquan
 *
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    
    @Autowired
    private PasswordExpired passwordExpired;
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao
    @Autowired
    private UserMngOrgMapper userMngOrgMapper;
    @Resource(name = "sysUserMngOrgService")
    private SysUserMngOrgService sysUserMngOrgService;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserStationMapper userStationMapper;

    @Autowired
    private UserAuthDataMapper userAuthDataMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Resource(name = "sysUserRoleService")
    private SysUserRoleService sysUserRoleService;

    @Resource(name = "sysUserStationService")
    private SysUserStationService sysUserStationService;

    @Resource(name = "sysUserAuthDataService")
    private SysUserAuthDataService sysUserAuthDataService;

    @Resource(name = "orgService")
    private OrgService orgService;
    
    @Autowired
    private RedisSessionDAO redisSessionDAO;

    @Override
    public PageUtils queryPage(Map<String, Object> params, UserVO userVO) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
//		JSONObject dataForm = JSONObject.fromObject(params.get("dataForm"));
        Map<String, Object> paramsNew = new HashMap<>();

        if (params.get("username") != null && !"".equals(params.get("username"))) {
            paramsNew.put("username", "%" + params.get("username").toString() + "%");
        }
        if (params.get("staffName") != null && !"".equals(params.get("staffName"))) {
            paramsNew.put("staffName", "%" + params.get("staffName").toString() + "%");
        }
        if (params.get("staffId") != null && !"".equals(params.get("staffId"))) {
            paramsNew.put("staffId", "%" + params.get("staffId").toString() + "%");
        }
        if (StringUtils.isNotBlank(params.get("orgId"))) {
            Org org = orgMapper.selectByPrimaryKey(params.get("orgId").toString());
            if(org != null){
                paramsNew.put("orgId", params.get("orgId").toString());
            }
        }
        paramsNew.put("userId", userVO.getId());
        paramsNew.put("statusDel", Constant.USER_STATUS_DELETED);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        List<Map<String, Object>> list = userMapper.selectByParams(paramsNew);
        pageUtils = new PageUtils(p);
        pageUtils.setList(MapCaseUtil.mapKeyToLowerCase(list));
        return pageUtils;
    }

    /**
     * 修改密码
     * @param userVO
     * @param password
     * @param newPassword
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(UserVO userVO, String password, String newPassword) {
        UserVO userNew = new UserVO();
        String getNowPassWord = userVO.getPassword();
        userVO.setPassword(password);
        userVO = PasswordHelper.encryptPassword(userVO);
        Date date = new Date();
        if (getNowPassWord.equals(userVO.getPassword())) {
            BeanUtils.copyProperties(userVO, userNew);
            userNew.setPassword(newPassword);
            userNew = PasswordHelper.encryptPassword(userNew);
            userNew.setLastChangeder(userVO.getId());
            userNew.setLastChnagedTime(date);
            userNew.setLastChangedPwdTime(date);
            userMapper.updateByPrimaryKey(userNew);
            return true;
        }
        return false;
    }

    /**
     * 重置密码
     * @param userId
     * @param opUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String resetPassword(String userId, UserVO opUser) {
        User user = userMapper.selectByPrimaryKey(userId);
        //生成随机密码
        String passNew = PasswordHelper.generatePassword(10);
        UserVO userNew = new UserVO();
        BeanUtils.copyProperties(user, userNew);
        userNew.setPassword(passNew);
        userNew = PasswordHelper.encryptPassword(userNew);
        Date date = new Date();
        userNew.setLastChangeder(opUser.getId());
        userNew.setLastChnagedTime(date);
        userNew.setLastChangedPwdTime(date);
        userMapper.updateByPrimaryKey(userNew);
        return passNew;
    }

    /**
     * 判断用户名是否可用，返回true代表不可用
     * @param username
     * @param tenantId
     * @return
     */
    @Override
    public boolean checkUserName(String username, String tenantId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andTenantIdEqualTo(tenantId);
        List<User> list = userMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict={@CacheEvict(value="mngOrg", allEntries = true), @CacheEvict(value = "orgs", allEntries = true)})
    public void save(User user, JSONArray mngOrgArr) {
        Date dateNow = new Date();
        user.setId(UuidUtil.get32UUID());
        user.setPassword(passwordExpired.getDefaultPassword());
        user.setCreateTime(dateNow);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO = PasswordHelper.encryptPassword(userVO);
        user.setPassword(userVO.getPassword());
        user.setSalt(userVO.getSalt());
        //userMapper.insert(userVO);
        userMapper.insertSelective(user);
        this.saveUserRelationInf(user, mngOrgArr);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict={@CacheEvict(value="mngOrg", allEntries = true), @CacheEvict(value = "orgs", allEntries = true)})
    public void update(User user, JSONArray mngOrgArr, String moduleType) {
        Date dateNow = new Date();
        user.setLastChnagedTime(dateNow);
        userMapper.updateByPrimaryKeySelective(user);
        sysUserMngOrgService.deleteByUserId(user.getId());
        sysUserRoleService.deleteByUserIdAndModuleType(user.getId(), moduleType);
        sysUserStationService.deleteByUserIdAndModuleType(user.getId(), moduleType);
        sysUserAuthDataService.deleteByUserIdAndModuleType(user.getId(), moduleType);
        this.saveUserRelationInf(user, mngOrgArr);
    }

    /**
     * 根据orgCode查询没同步的用户（来自账户系统的数据），分页
     *
     * @param params
     * @param userVO
     * @return
     */
    @Override
    public PageUtils queryPageListTemp(Map<String, Object> params, UserVO userVO) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        String parentId = params.get("parentId").toString().trim();
        Org org = orgService.selectById(parentId);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        List<Map<String, Object>> list =  userMapper.selectListTemp(org.getOrgCode());
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /**
     * 将账户系统同步过来的用户数据入库
     *
     * @param param
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importUsersFromAccount(Map param, UserVO user) {
        String id = param.get("orgId").toString();
        List<Object> users = (List<Object>) param.get("userIds");
        Org org = orgService.selectById(id);
        List<Map<String, Object>> auList = userMapper.selectListFromAccountTemp(users);
        for(Map<String, Object> map : auList){
            User userIn = new User();
            userIn.setId(UuidUtil.get32UUID());
            userIn.setOrgId(id);
            userIn.setStatus(Constant.USER_STATUS_NORMAL);
            userIn.setUsername(map.get("account").toString());
            userIn.setCreateTime(new Date());
            userIn.setCreateUserId(user.getId());
            userIn.setEmail(map.get("email_addr") == null ? null : map.get("email_addr").toString());
            userIn.setRelationType("1");
            userIn.setSkin("blue");
            userIn.setStaffName(map.get("user_name") == null ? null : map.get("user_name").toString());
            userIn.setTenantId(Constant.SUPER_ADMIN_TENANTID);
            userIn.setAccountName(map.get("account").toString());
            userIn.setEnterpriseId(map.get("society_code").toString());
            userIn.setEnterpriseName(map.get("org_name") == null ? null : map.get("org_name").toString());
            userIn.setStaffId(map.get("account").toString());
            userIn.setType("1");
            userIn.setPassword(passwordExpired.getDefaultPassword());
//            userIn = PasswordHelper.encryptPassword(userIn);
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(userIn, vo);
            vo = PasswordHelper.encryptPassword(vo);
            userIn.setPassword(vo.getPassword());
            userIn.setSalt(vo.getSalt());
            userMapper.insertSelective(userIn);
        }
    }

    /**
     * 获取机构下用户信息
     * @param orgId
     * @return
     */
    @Override
    public List<User> getUserListByOrgId(String orgId) {
        List<User> list = new ArrayList<>();
        //获取这个机构下
        this.getUserListBelongOrgId(list,orgId);
        return list;
    }

    /**
     * 批量调整用户部门
     *
     * @param param
     * @param user
     */
    @Override
    public void changeUsersDept(UserDeptChange param, UserVO user) {
        Org org = orgService.selectById(param.getOrgId());
        for(String userId : param.getUserIds()){
            UserVO user1 = new UserVO();
            user1.setId(userId);
            user1.setOrgId(org.getId());
            user1.setEnterpriseId(org.getOrgCode());
            user1.setEnterpriseName(org.getOrgName());
            user1.setLastChangeder(user.getId());
            user1.setLastChnagedTime(new Date());
            userMapper.updateByPrimaryKeySelective(user1);
        }
    }

    /**
     * 获取机构下用户
     * @param list
     * @param orgId
     * @return
     */
    public List<User> getUserListBelongOrgId(List<User>list,String orgId){
        //获取本机构下用户信息
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andOrgIdEqualTo(orgId);
        //过滤正常状态
        criteria.andStatusEqualTo(Constant.USER_STATUS_NORMAL);
        userExample.setOrderByClause("order_num");
        List<User> userList = userMapper.selectByExample(userExample);
        list.addAll(userList);//放到list里面
        //获取当前机构的下级部门
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria orgCriteria = orgExample.createCriteria();
        orgCriteria.andParentIdEqualTo(orgId);
        orgCriteria.andOrgRankEqualTo("2");//部门
        List<Org> orgList = orgMapper.selectByExample(orgExample);
        for (Org org : orgList) {
            String id = org.getId();
            this.getUserListBelongOrgId(list,id);
        }
        return list;

    }

    private void saveUserRelationInf(User user, JSONArray mngOrgArr) {
        for (int i = 0; i < mngOrgArr.size(); i++) {
            UserMngOrg userMngOrg = new UserMngOrg();//管辖部门
            JSONObject mngOrgJo = mngOrgArr.getJSONObject(i);
            userMngOrg.setId(UuidUtil.get32UUID());
            userMngOrg.setOrgId(mngOrgJo.getString("orgId"));
            userMngOrg.setUserId(user.getId());
            userMngOrg.setDefaultState(mngOrgJo.getString("defaultState"));
            userMngOrgMapper.insert(userMngOrg);

            JSONArray roleDataArr = mngOrgJo.getJSONArray("roleDatas");
            for (int x = 0; x < roleDataArr.size(); x++) {
                UserRole userRole = new UserRole();//角色
                userRole.setId(UuidUtil.get32UUID());
                userRole.setUserId(user.getId());
                userRole.setOrgId(userMngOrg.getOrgId());
                userRole.setRoleId(roleDataArr.getJSONArray(x).getString(1));
                userRoleMapper.insert(userRole);
            }

            JSONArray stationDataArr = mngOrgJo.getJSONArray("stationDatas");
            for (int y = 0; y < stationDataArr.size(); y++) {
                UserStation userStation = new UserStation();//岗位
                userStation.setId(UuidUtil.get32UUID());
                userStation.setUserId(user.getId());
                userStation.setOrgId(userMngOrg.getOrgId());
                userStation.setStationId(stationDataArr.getJSONArray(y).getString(1));
                userStationMapper.insert(userStation);
            }


            JSONArray authDataArr = mngOrgJo.getJSONArray("authDatas");
            for (int z = 0; z < authDataArr.size(); z++) {
                UserAuthData userAuthData = new UserAuthData();//数据权限
                userAuthData.setId(UuidUtil.get32UUID());
                userAuthData.setOrgId(userMngOrg.getOrgId());
                userAuthData.setUserId(user.getId());
                userAuthData.setModuleType(authDataArr.getJSONObject(z).getString("moduleType"));
                userAuthData.setDataLevel(authDataArr.getJSONObject(z).getString("dataLevel"));
                userAuthData.setOrgProp("1");//1是管辖部门
                userAuthData.setDataIndex(z);
                userAuthDataMapper.insert(userAuthData);
            }
        }
    }

    /**
     * 根据id获取用户信息
     * @param userId
     * @return
     */
    @Override
    public User selectById(String userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setPassword(null);
        user.setSalt(null);
        return user;
    }


    /**
     * 删除用户，逻辑删除
     * @param userIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict={@CacheEvict(value="mngOrg", allEntries = true), @CacheEvict(value = "orgs", allEntries = true)})
    public void deleteBatch(String[] userIds) {
        //删掉管理信息（角色、岗位、管辖企业）
        List<String> list = Arrays.asList(userIds);
        UserMngOrgExample example1 = new UserMngOrgExample();
        UserMngOrgExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUserIdIn(list);
        userMngOrgMapper.deleteByExample(example1);

        UserRoleExample example2 = new UserRoleExample();
        UserRoleExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andUserIdIn(list);
        userRoleMapper.deleteByExample(example2);

        UserStationExample example3 = new UserStationExample();
        UserStationExample.Criteria criteria3 = example3.createCriteria();
        criteria3.andUserIdIn(list);
        userStationMapper.deleteByExample(example3);

        UserAuthDataExample example4 = new UserAuthDataExample();
        UserAuthDataExample.Criteria criteria4 = example4.createCriteria();
        criteria4.andUserIdIn(list);
        userAuthDataMapper.deleteByExample(example4);

        for (String id : userIds) {
            User user = new User();
            user.setId(id);
            user.setStatus(Constant.USER_STATUS_DELETED);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    /**
     * 获取用户岗位信息
     * @param userId
     * @return
     */
    @Override
    public List<UserStation> getUserStationList(String userId) {
        UserStationExample example1 = new UserStationExample();
        UserStationExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUserIdEqualTo(userId);
        return userStationMapper.selectByExample(example1);
    }

    /**
     * 设置用户岗位
     * @param userId 用户id
     * @param stationList 岗位列表
     * @param userOp 操作人
     */
    @Override
    public void setUserStation(String userId, List<UserStation> stationList, UserVO userOp) {
        // 先删掉原来的岗位关联
        UserStationExample example1 = new UserStationExample();
        UserStationExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUserIdEqualTo(userId);
        userStationMapper.deleteByExample(example1);
        for (UserStation userStation : stationList) {
            userStationMapper.insert(userStation);
        }

    }

    /**
     * 查找所有的用户
     * @param tenantId
     * @return
     */
    @Override
    public List<User> getAllUserByTenantId(String tenantId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andTenantIdEqualTo(tenantId);
        criteria.andStatusEqualTo(Constant.USER_STATUS_NORMAL);
        List<User> list = userMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<User> getAllUserByStationIds(String stationIds) {

        UserStationExample example1 = new UserStationExample();
        UserStationExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andStationIdIn(Arrays.asList(stationIds.split(",")));
        List<UserStation> userStations = userStationMapper.selectByExample(example1);
        if(userStations.isEmpty()){
            return new ArrayList<User>();
        }
        List<String> userIds = new ArrayList<>();
        for (UserStation userStation : userStations) {
            userIds.add(userStation.getUserId());
        }
        UserExample example2 = new UserExample();
        UserExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdIn(userIds);
        return userMapper.selectByExample(example2);
    }

    /**
     * 内部处理数据用，请注掉
     *
     * @return
     */
    @Override
    public String resetPasswordBath() {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdNotEqualTo("1");
        List<User> list = userMapper.selectByExample(example);
        long l = list.stream().map(m -> {
            UserVO userNew = new UserVO();
            BeanUtils.copyProperties(m, userNew);
            userNew.setPassword(passwordExpired.getDefaultPassword());
            userNew = PasswordHelper.encryptPassword(userNew);
            userMapper.updateByPrimaryKey(userNew);
            return m;
        }).count();
        return String.valueOf(l);
    }
    
    /**
     * 根据id查询用户
     *
     * @param userIds
     * @return
     */
    @Override
    public List<User> getUsersOnly(List<String> userIds){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(userIds);
        return userMapper.selectByExample(example);
}
    
    /**
     * 把密码重置为初始密码（你懂的）
     * @param userId 用户id
     * @return ok
     */
    @Override
    public String resetPasswordSimple(String userId){
        User user = userMapper.selectByPrimaryKey(userId);
        //who knows
        SymmetricCrypto sm4 = SmUtil.sm4("yaCwhLFbOy2Tm1fN".getBytes(CharsetUtil.CHARSET_UTF_8));
        String lastWeekNo12Mi = "7d71c609479eed1599a280642981a2e2";
        UserVO userNew = new UserVO();
        BeanUtils.copyProperties(user, userNew);
        userNew.setPassword(sm4.decryptStr(lastWeekNo12Mi));
        userNew = PasswordHelper.encryptPassword(userNew);
        userMapper.updateByPrimaryKey(userNew);
        return "ok";
    }
    
    /**
     * 系统管理员查用户
     *
     * @param params params {username:,staffName:,enterpriseName:,orgCode:,orgName,staffId:,status:}
     * @param userVO 用户
     * @return 分页数据
     */
    @Override
    public PageUtils queryPageAdmin(Map<String, Object> params, UserVO userVO){
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        Map<String, Object> paramsNew = new HashMap<String, Object>();
    
        if (params.get("username") != null && !"".equals(params.get("username"))) {
            paramsNew.put("username", "%" + params.get("username").toString() + "%");
        }
        if (params.get("staffName") != null && !"".equals(params.get("staffName"))) {
            paramsNew.put("staffName", "%" + params.get("staffName").toString() + "%");
        }
        if (params.get("staffId") != null && !"".equals(params.get("staffId"))) {
            paramsNew.put("staffId", "%" + params.get("staffId").toString() + "%");
        }
        if (params.get("enterpriseName") != null && !"".equals(params.get("enterpriseName"))) {
            paramsNew.put("enterpriseName", "%" + params.get("enterpriseName").toString() + "%");
        }
        if (params.get("orgCode") != null && !"".equals(params.get("orgCode"))) {
            paramsNew.put("orgCode", "%" + params.get("orgCode").toString() + "%");
        }
        if (params.get("orgName") != null && !"".equals(params.get("orgName"))) {
            paramsNew.put("orgName", "%" + params.get("orgName").toString() + "%");
        }
        if (StringUtils.isNotBlank(params.get("orgId"))) {
            paramsNew.put("orgId", params.get("orgId").toString());
        }
        if (StringUtils.isNotBlank(params.get("status"))) {
            paramsNew.put("status", params.get("status").toString());
        }
        List<Map<String, Object>> list = MapCaseUtil.mapKeyToLowerCase(userMapper.selectByParamsAdmin(paramsNew));
        list = list.stream().peek(m -> {
            List<Map<String, Object>> listMng = userMngOrgMapper.selectUserMngOrgByUserHasParentName(m.get("id").toString());
            m.put("mgnOrgs", listMng.stream().map(lm -> {
                Map<String, String> nm = new HashMap<>();
                if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(lm.get("org_rank"))){
                    nm.put("companyName", (String) lm.get("pname"));
                    nm.put("deptName", (String) lm.get("org_name"));
                }else{
                    nm.put("companyName", (String) lm.get("org_name"));
                    nm.put("deptName", null);
                }
                return nm;
            }).collect(Collectors.toList()));
        }).collect(Collectors.toList());
        pageUtils = new PageUtils(p);
        pageUtils.setList(list);
        return pageUtils;
    }
    
    /**
     * 将状态为删除的用恢复回来变成状态正常的
     *
     * @param id 用户id
     */
    @Override
    public void rollbackUser(String id){
        User user = new User();
        user.setId(id);
        user.setStatus(Constant.USER_STATUS_NORMAL);
        userMapper.updateByPrimaryKeySelective(user);
    }
    
    /**
     * 物理删除用户，慎用
     *
     * @param id 用户id
     */
    @Override
    public void deletePhysical(String id){
        if (Constant.SUPER_ADMIN.equals(id)) {
            throw new BusinessException("系统管理员不能删除");
        }
        userMapper.deleteByPrimaryKey(id);
    }
    
    /**
     * 根据accountName查询用户
     *
     * @param accountName accountName
     * @return 用户
     */
    @Override
    public User selectByAccount(String accountName){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andAccountNameEqualTo(accountName);
        List<User> list = userMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 根据staffId查询用户
     *
     * @param staffId String
     * @return 用户
     */
    @Override
    public User selectByStaffId(String staffId){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andStaffIdEqualTo(staffId);
        List<User> list = userMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 根据userName查询用户
     *
     * @param userName String
     * @return 用户
     */
    @Override
    public User selectByUserName(String userName){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(userName);
        List<User> list = userMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }
    
    /**
     * 统计用户信息
     *
     * @return 用户统计信息
     */
    @Override
    public UserStatistics userStatistics(){
        Collection<Session> sessions = redisSessionDAO.getActiveSessions();
        UserStatistics statistics = new UserStatistics();
        //在线用户数量
        statistics.setOnline(sessions.size());
        List<Map<String, Object>> total = sqlAdapterMapper.selectSQL("select count(id) as total from sys_user");
        //用户总数
        statistics.setTotal((Long) total.get(0).get("total"));
        List<Map<String, Object>> normal = sqlAdapterMapper.selectSQL("select count(id) as normal from sys_user where `status`='" + Constant.USER_STATUS_NORMAL + "'");
        //正常状态的
        statistics.setNormal((Long) normal.get(0).get("normal"));
        List<Map<String, Object>> locked = sqlAdapterMapper.selectSQL("select count(id) as locked from sys_user where `status`='" + Constant.USER_STATUS_LOCKED + "'");
        //锁定状态的
        statistics.setNormal((Long) locked.get(0).get("locked"));
        List<Map<String, Object>> disabled = sqlAdapterMapper.selectSQL("select count(id) as disabled from sys_user where `status`='" + Constant.USER_STATUS_DISABLED + "'");
        //禁用状态的
        statistics.setNormal((Long) disabled.get(0).get("disabled"));
        List<Map<String, Object>> deleted = sqlAdapterMapper.selectSQL("select count(id) as deleted from sys_user where `status`='" + Constant.USER_STATUS_DELETED + "'");
        //删除状态的
        statistics.setNormal((Long) deleted.get(0).get("deleted"));
        return statistics;
    }
    
}
